package com.swak.devtools.config;

import java.util.List;
import java.util.Set;

import com.swak.devtools.apidoc.entity.Api;
import com.swak.devtools.apidoc.entity.Apis;
import com.swak.devtools.apidoc.parse.ApiClass;
import com.swak.devtools.apidoc.parse.ApiMethod;
import com.swak.devtools.apidoc.parse.parser.ClassParser;
import com.swak.devtools.apidoc.utils.ApiID;
import com.swak.utils.Sets;
import com.swak.vertx.config.RouterBean;
import com.swak.vertx.config.VertxConfigs;

import lombok.Getter;

/**
 * RouterInitialize.
 */
public class DevtoolsApiInitialize {

	public static DevtoolsApiInitialize Holder = null;

	@Getter
	private final Apis router;

	public DevtoolsApiInitialize() {
		this.router = new Apis();
		Holder = this;
	}

	public void initializer() {
		List<RouterBean> beans = VertxConfigs.me().getConfigs().stream().filter(bean -> bean instanceof RouterBean)
				.map(bean -> (RouterBean) bean).toList();

		// 所有的Api
		Set<Class<?>> apiClasses = Sets.newOrderSet();
		for (RouterBean bean : beans) {
			apiClasses.add(bean.getType());
		}

		for (Class<?> type : apiClasses) {
			ApiClass apiClass = ClassParser.parse(type);
			List<ApiMethod> apiMethods = apiClass.getApiMethods();
			for (ApiMethod apiMethod : apiMethods) {
				Set<String> paths = apiMethod.getApiRequestPaths();
				if (paths != null && !paths.isEmpty()) {
					for (String path : paths) {
						this.router.addRoute(this.buildRoute(path, apiMethod));
					}
				}
			}
		}
	}

	private Api buildRoute(String path, ApiMethod method) {

		// 基本信息
		Api route = new Api() // 路由
				.setId(ApiID.genID(method.getApiRequestMethod(), path))// 路由ID
				.setRequestPath(path) // 请求URL
				.setRequestMethod(method.getApiRequestMethod());// 请求方法

		// 返回路由
		return route.setInfo(method);
	}
}
